package cn.appsys.controller.backend;

import cn.appsys.pojo.BackendUser;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.service.developer.DataDictionaryService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping(value = "/manager/backend/datadictionary")
public class DataDictionaryController {


    @Resource
    DataDictionaryService dataDictionaryService;

    @RequestMapping(value = "/list")
    public String list(Model model, DataDictionary dataDictionary,
                       @RequestParam(value = "pageIndex", required = false) String pageIndex) {


        System.out.println(dataDictionary);

        //当前页码
        Integer currentPageNo = 1;
        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        List<DataDictionary> list = null;
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        try {
            list = dataDictionaryService.getList(dataDictionary, pages);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //总数量（表）
        int totalCount = 0;
        try {
            totalCount = dataDictionaryService.getCount(dataDictionary);
        } catch (Exception e) {
            e.printStackTrace();
        }

        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        model.addAttribute("list", list);
        model.addAttribute("pages", pages);
        model.addAttribute("valueName",dataDictionary.getValueName());//回显的作用
        model.addAttribute("typeCode",dataDictionary.getTypeCode());//回显的作用
        return "backend/datadictionary/list";
    }

    @ResponseBody
    @RequestMapping(value = "/getgrouptype.json")
    public Object getGroupType() {
        List<DataDictionary> list = null;
        try {
            list = dataDictionaryService.getGroupTypeService();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONArray.toJSON(list);
    }
}
